package com.norns.torque.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.gyf.immersionbar.ImmersionBar
import com.hi.dhl.binding.viewbind
import com.norns.torque.R
import com.norns.torque.WifiDeviceViewModel
import com.norns.torque.databinding.ActivityWifiDeviceBinding
import com.norns.torque.databinding.ItemFootBinding
import com.norns.torque.databinding.ItemWifiDeviceBinding
import com.norns.torque.dialog.AddDeviceDialog
import com.norns.torque.dialog.LoadingDialog
import com.norns.torque.entrty.WifiDevice
import com.norns.torque.network.NetworkListenerHelper
import com.norns.torque.network.NetworkStatus
import com.norns.torque.network.NetworkUtils
import com.norns.torque.utils.AppConstant
import com.norns.torque.utils.AppContext

class WiFiDeviceActivity : AppCompatActivity() {
    private val binding: ActivityWifiDeviceBinding by viewbind()
    private val deviceList: ArrayList<WifiDevice> = ArrayList()
    private val viewModel: WifiDeviceViewModel by viewModels()
    private var loadingDialog: LoadingDialog? = null
    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase)
        overrideFontScale(newBase)
    }

    /**
     * 重置配置 fontScale：保持字体比例不变，始终为 1.
     */
    private fun overrideFontScale(context: Context?) {
        if (context == null) return
        context.resources.configuration.let {
            it.fontScale = 1f // 保持字体比例不变，始终为 1.
            applyOverrideConfiguration(it) // 应用新的配置
        }
    }

    private var networkListenerHelper = object : NetworkListenerHelper.NetworkConnectedListener {
        override fun onNetworkConnected(isConnected: Boolean, networkStatus: NetworkStatus) {
            if (!isConnected || networkStatus != NetworkStatus.WIFI) {
                Toast.makeText(this@WiFiDeviceActivity, "wifi已断开", Toast.LENGTH_SHORT).show()
                viewModel.setDeviceUnConnected()
            }else{
                viewModel.getAllDevice()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initData()
        subscribeToModel()
    }

    private fun initView() {
        ImmersionBar.with(this).statusBarColor(R.color.main)
            .navigationBarColor(R.color.white)
            .autoStatusBarDarkModeEnable(true, 0.2f)
            .init()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.btnBack.setOnClickListener { finish() }
        binding.btnMore.setOnClickListener { finish() }
        binding.tvAddDevice.setOnClickListener {
            AddDeviceDialog.newInstance().show(supportFragmentManager, "AddDeviceDialog")
        }
        binding.bluetoothList.divider {
            setDivider(5, true)
            endVisible = true
        }.linear()
            .setup {
                addType<WifiDevice> {
                    if (type == "foot") {
                        R.layout.item_foot
                    } else {
                        R.layout.item_wifi_device
                    }
                }
                onBind {
                    when (itemViewType) {
                        R.layout.item_wifi_device -> {
                            val binding =
                                getBinding<ItemWifiDeviceBinding>() // ViewBinding/DataBinding都支持
                            val data = getModel<WifiDevice>()
                            binding.tvDeviceName.text = data.name
                            binding.tvDeviceMac.text = data.address
                            binding.tvContentState.text = data.contentState
                            binding.tvDistance.text = "0dBm"
                            binding.tvContent.isEnabled = data.contentState != "离线"
                        }

                        R.layout.item_foot -> {
                            val binding = getBinding<ItemFootBinding>()
                            binding.tvFoot.text = "暂无设备"
                        }
                    }
                }

                R.id.tvContent.onClick {
                    val netWorkState = NetworkUtils.getNetWorkState(AppContext.context)
                    if (netWorkState != NetworkStatus.WIFI) {
                        Toast.makeText(this@WiFiDeviceActivity, "wifi已断开,请重新连接", Toast.LENGTH_SHORT)
                            .show()
                    } else {
                        val device = getModel<WifiDevice>()
                        if (device.address.isNullOrEmpty().not()) {
                            loadingDialog = LoadingDialog.newInstance("正在连接...")
                            loadingDialog!!.show(supportFragmentManager, "LoadingDialog")
                            viewModel.contentToDevice(device)
                        }
                    }
                }
                R.id.btnDelete.onClick {
                    val data = getModel<WifiDevice>()
                    viewModel.deleteDevice(data)
                }
            }
        binding.bluetoothList.models = deviceList
    }

    private fun initData() {
        viewModel.initDataBase()
    }

    private fun subscribeToModel() {
        NetworkListenerHelper.addListener(networkListenerHelper)
        viewModel.connectionState.observe(this) { value ->
            if (value == AppConstant.connectionSuccess) {//连接成功
                hidLoadingDialog()
                val intent = Intent(this@WiFiDeviceActivity, PeakValueActivity::class.java)
                startActivity(intent)
                finish()
            } else if (value == AppConstant.connectionField) {//连接失败
                hidLoadingDialog()
                Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show()
            }
        }
        viewModel.deviceListLiveData.observe(this) { list ->
            hidLoadingDialog()
            binding.bluetoothList.models = list
        }

        viewModel.deviceLiveData.observe(this) { device ->
            val deviceList = binding.bluetoothList.models as List<WifiDevice>
            deviceList.forEachIndexed { index, wifiDevice ->
                val result = (device.address == wifiDevice.address)
                if (result) {
                    wifiDevice.contentState = device.contentState
                    binding.bluetoothList.bindingAdapter.notifyItemChanged(index)
                    return@forEachIndexed
                }
            }
        }
    }

    override fun onDestroy() {
        hidLoadingDialog()
        NetworkListenerHelper.removeListener(networkListenerHelper)
        super.onDestroy()
    }

    private fun hidLoadingDialog() {
        if (null!=loadingDialog){
            loadingDialog?.dismiss()
            loadingDialog = null
        }
    }

}